package com.tfswx.sjkbbgl.core.autoconfigure;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.*;

import java.util.Properties;

/**
 * @author ricky
 * @date 2022/3/12
 */
public class LiquibaseEnvironmentPostProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

        MutablePropertySources propertySources = environment.getPropertySources();
        String jdbcUrl = null;
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource.containsProperty("spring.datasource.url")) {
                Object url = propertySource.getProperty("spring.datasource.url");
                if (url == null) {
                    continue;
                }
                if (StringUtils.isNotBlank(String.valueOf(url))) {
                    jdbcUrl = String.valueOf(url);
                    break;
                }
            }
        }
        if (StringUtils.isBlank(jdbcUrl)) {
            System.err.println("没有配置spring.datasource.url");
            System.exit(1);
        }

        Properties liquibaseProperties = new Properties();
        liquibaseProperties.setProperty("spring.liquibase.clearChecksums", "false");
        liquibaseProperties.setProperty("spring.liquibase.dropFirst", "false");
        liquibaseProperties.setProperty("spring.liquibase.databaseChangeLogTable", "CHANGELOG");
        liquibaseProperties.setProperty("spring.liquibase.databaseChangeLogLockTable", "CHANGELOGLOCK");
        liquibaseProperties.setProperty("spring.liquibase.change-log", "classpath:/db/changelog/db.changelog-master.xml");

        String sjklx = "";
        if (jdbcUrl.startsWith("jdbc:mysql")) {
            sjklx = "mysql";
        } else if (jdbcUrl.startsWith("jdbc:dm")) {
            sjklx = "dm";
        } else if (jdbcUrl.startsWith("jdbc:sqlite")) {
            sjklx = "sqlite";
        } else {
            System.err.println("目前仅支持【MySQL】、【DM】、【SQLite】，其余数据库暂未进行测试");
            System.exit(1);
        }
        liquibaseProperties.setProperty("spring.liquibase.parameters.sjklx", sjklx);

        propertySources.addFirst(new PropertiesPropertySource("liquibase.properties", liquibaseProperties));
    }
}
